package com.azkj.album.view.widgets.dialog;

import android.app.Dialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.core.app.NotificationCompat;

import com.azkj.album.BuildConfig;
import com.azkj.album.R;
import com.azkj.album.dto.UpdateBean;
import com.azkj.album.network.NetworkMaster;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.utils.DensityUtils;
import com.azkj.album.utils.DownLoadApkUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.Timer;
import java.util.TimerTask;


public class UpdateAppDialog {


    public static final class Builder {
        private NotificationManager notificationManager;
        private NotificationCompat.Builder builder;
        private NotificationClickReceiver notificationClickReceiver;


        public Context mContext;
        private Dialog dialog;

        private UpdateBean mUpdateBean;

        private TextView mTvContent;
        private TextView mTvTitle;
        private TextView mTvConfirm;
        private TextView mTvCancel;
        private String downLoadUrl;


        //0:未开始 1：下载中，2：完成，-1：失败
        private int downloadState;
        private File apkFile;
        private static String TAG = "UpdataAppDialog";
        private float mfProgress;
        private Timer timer;
        OnUpdateCallback onUpdateCallback;


        public Builder(Context context) {
            this.mContext = context;
            View view = LayoutInflater.from(context).inflate(
                    R.layout.dialog_update, null);
            mTvContent = view.findViewById(R.id.tv_content);
            mTvTitle = view.findViewById(R.id.tv_title);
            mTvConfirm = view.findViewById(R.id.tv_confirm);
            mTvCancel = view.findViewById(R.id.tv_cancel);


            // 定义Dialog布局和参数
            dialog = new Dialog(context, R.style.MyDialog);
            dialog.setContentView(view);
            Window dialogWindow = dialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.x = 0;
            lp.y = 0;
            lp.width = (int) (DensityUtils.getScreenWidth(context));
            lp.height = (int) (DensityUtils.getScreenHeight(context));
            lp.gravity = Gravity.CENTER;
            dialogWindow.setAttributes(lp);
        }

        public Builder setUpdateBean(UpdateBean updateBean) {
            this.mUpdateBean = updateBean;
            downLoadUrl = mUpdateBean.getAndroid_download_url();
//            downLoadUrl = "https://cddongping.com" + mUpdateBean.getAndroid_download_url();

            initNotification();
            registerReceiver();
            initData();
            return this;
        }

        private void initData() {


            if (BuildConfig.VERSION_CODE >= mUpdateBean.getAndroid_version()) {

                mTvTitle.setText("当前版本为最新版本！");
                mTvConfirm.setOnClickListener(v -> this.dialog.dismiss());
            } else {

                mTvTitle.setText("发现新版本，为了您更好的使用软件请下载更新！");
                mTvContent.setText("(如果安装失败请到应用市场手动更新)");
                mTvCancel.setVisibility(View.VISIBLE);
                mTvCancel.setOnClickListener(v -> this.dialog.dismiss());

                mTvConfirm.setOnClickListener(v -> {
                    if (onUpdateCallback != null) onUpdateCallback.onConfirm();
                    this.dialog.dismiss();
                });
            }


        }


        public Builder show() {
            dialog.show();
            return this;

        }

        public Builder download() {
            if (downloadState != 1) {//应用内直接下载，通知栏显示进度，完成后安装
                downLoadApk();
            } else {
                ToastUtils.showCenterToast("下载中，请在通知栏查看进度");
            }
            return this;
        }


        /**
         * 设置dialog 回调
         */
        public Builder setUpdateListener(OnUpdateCallback callback) {
            onUpdateCallback = callback;
            return this;
        }


        /**
         * 下载apk
         */
        private void downLoadApk() {
            try {
                //此情况适用于 文件下载成功，但取消安装，app不退出的情况下
                //再次点击就不再重新下载，直接安装。
                if (apkFile != null && apkFile.exists()) {
                    DownLoadApkUtils.installApk(mContext, downLoadUrl, apkFile);
                    return;
                }

                File folder = new File(mContext.getExternalCacheDir().getAbsoluteFile().getPath() + File.separator + "downloads");
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                apkFile = new File(folder.getPath() + File.separator + System.currentTimeMillis() + "saleform.apk");

                if (apkFile.exists()) {
                    apkFile.delete();
                    apkFile.createNewFile();
                }
                ToastUtils.showCenterToast("开始下载，请在通知栏查看进度");
                downloadState = 1;
                mfProgress = 0;
                notificationManager.notify(100, builder.build());
                startTimer();
                DownLoadApkUtils.download(downLoadUrl, apkFile, new DownLoadApkUtils.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess() {
                        Log.d(TAG, "onDownloadSuccess");
                        downloadState = 2;
                        notificationManager.cancel(100);
                        DownLoadApkUtils.installApk(mContext, downLoadUrl, apkFile);

                    }

                    @Override
                    public void onDownloading(float progress) {
                        Log.d(TAG, "onDownloading  : " + progress);
                        downloadState = 1;
                        mfProgress = new BigDecimal(progress).setScale(1, BigDecimal.ROUND_HALF_DOWN).floatValue();

                    }

                    @Override
                    public void onDownloadFailed(String msg) {
                        Log.d(TAG, "onDownloadFailed");
                        downloadState = -1;
                        mfProgress = -1;
                        if (apkFile != null && apkFile.exists()) {
                            apkFile.delete();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        /**
         * 初始化通知
         */
        private void initNotification() {
            try {
                notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
                // Android8.0及以后的方式
                if (Build.VERSION.SDK_INT >= 26) {
                    // 创建通知渠道
                    NotificationChannel notificationChannel = new NotificationChannel("download_channel", "下载",
                            NotificationManager.IMPORTANCE_DEFAULT);
                    notificationChannel.enableLights(false); //关闭闪光灯
                    notificationChannel.enableVibration(false); //关闭震动
                    notificationChannel.setSound(null, null); //设置静音
                    notificationManager.createNotificationChannel(notificationChannel);
                }
                builder = new NotificationCompat.Builder(mContext, "download_channel");

                builder.setContentTitle("新版本上线") //设置标题
                        .setSmallIcon(mContext.getApplicationInfo().icon) //设置小图标
                        .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(),
                                mContext.getApplicationInfo().icon)) //设置大图标
                        .setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的优先级
                        .setAutoCancel(false) //设置通知被点击一次不自动取消
                        .setSound(null) //设置静音
                        .setContentText("0%") //设置内容
                        .setProgress(100, 0, false) //设置进度条
                        .setContentIntent(createIntent()); //设置点击事件

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 刷新通知
         *
         * @param progress 百分比，此值小于0时不刷新进度条
         */
        private void updateNotification(float progress) {
            if (builder == null) {
                return;
            }
            if (downloadState == -1 || progress == -1) {
                builder.setContentText("下载失败,点击重新下载");
                builder.setProgress(100, 0, false);
            } else if (progress == 100) {
                builder.setContentText("下载完成,点击安装");
                builder.setProgress(100, 100, false);
                builder.setAutoCancel(true);
            } else {
                builder.setContentText(progress + "%");
                builder.setProgress(100, (int) progress, false);
            }

            notificationManager.notify(100, builder.build());
        }

        /**
         * 设置通知点击事件
         *
         * @return 点击事件
         */
        private PendingIntent createIntent() {
            Intent intent = new Intent(mContext.getPackageName() + ".upgrade.notification");
            intent.setPackage(mContext.getPackageName());
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            return pendingIntent;
        }

        /**
         * 注册通知点击监听
         */
        private void registerReceiver() {
            notificationClickReceiver = new NotificationClickReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(mContext.getPackageName() + ".upgrade.notification");
            mContext.registerReceiver(notificationClickReceiver, intentFilter);
        }

        /**
         * 处理通知栏点击事件
         */
        public class NotificationClickReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (!(mContext.getPackageName() + ".upgrade.notification").equals(action)) {
                    return;
                }
                Log.d(TAG, "NotificationClickReceiver state = " + downloadState);
                switch (downloadState) {
                    case -1:
                        // 关闭通知栏
                        downLoadApk();
//                    notificationManager.cancel(100);
                        break;
                    case 2:
                        // 显示安装确认弹窗
                        DownLoadApkUtils.installApk(mContext, downLoadUrl, apkFile);
                        break;

                    default:
                        break;
                }
            }
        }

        public void startTimer() {
            timer = new Timer();
            TimerTask task = new TimerTask() {

                public void run() {
                    updateNotification(mfProgress);
                    if (mfProgress == -1 || mfProgress == 100) {
                        timer.cancel();
                        timer = null;
                    }
                }
            };
            timer.schedule(task, 0L, 1000L);
        }
    }

    /**
     * dialog 回调
     */
    public interface OnUpdateCallback {
        void onConfirm();

    }

}
